package com.sykuku.interceptor;

import com.alibaba.fastjson.JSON;
import com.sykuku.common.BaseContext;
import com.sykuku.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("定义的验证登录拦截器");
        HttpSession session = request.getSession();
        Long username = (Long) session.getAttribute("employee");

        //手机端的
        Long user = (Long) request.getSession().getAttribute("user");

        if (username == null && user == null) {
            String s = JSON.toJSONString(R.error("NOTLOGIN"));
            response.getWriter().write(s);
            return false;
        }


        if (username != null) {
            //电脑端的用户id放进线程池 在类中自动填充那个用户修改
            BaseContext.setThreadLocalID(username);
            return true;
        }

        if (user != null) {
            //手机端的用户id放进线程池
            BaseContext.setThreadLocalID(user);
            return true;
        }

        log.info("拦截器中当前线程为{}", Thread.currentThread().getId());
        log.info("拦截器中已将获取到的用户id放入线程中");
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        log.info("清理当前线程{}对象中的数据", Thread.currentThread().getId());
        BaseContext.remove();
    }
}
